<template>
	<view class="content">
	    <!-- 公共组件-每个页面必须引入 -->
	    <public-module></public-module>
		<u-sticky bgColor="#fff">
				<u-tabs :list="tabs" lineColor="#FF5E01" :activeStyle="{color: '#FF5E01'}" :current="current" @change="changeTab" ref="tab" :scrollable="false">
						
				</u-tabs>
		  </u-sticky>
		  <div class="con-list-div" v-if="tab != 'set'">
				<div class="sale-list-item arrangeGoods-item" v-for="(item,index) in list" :key="index">
			<!-- 	 <div class="sale-top"  style="cursor: pointer">
					<div class="sale-compeny" style="cursor: pointer">{{item.invoiceTitle}}</div>
				  </div> -->
				  <div class="sale-con" style="cursor: pointer">
					 <div class="goods-top">
						 <div class="goods-name">{{item.goodsName}}</div>
						 <div class="goods-price">{{item.sendNum}}<span class="label">吨</span></div>
					 </div>
					 <div class="goods-middle">
						 <div class="goods-subtxt">订单编号：<span style="color:#409EFF;cursor: pointer;" @click="toOrder(item)">{{item.orderSn}}</span></div>
						 <div class="goods-subtxt"  v-if="tab == 'has'">
							 发票编号：
							 <span v-for="(ee,ii) in item.invoiceData" :key="ii" style="word-break: break-all;">
								 {{ee.invoiceCode}}
								 <span v-if="ii < item.invoiceData.length-1">,</span>
							 </span>
						 </div>
						 <div class="goods-subtxt"  v-if="tab == 'has'">
							开票时间：{{item.invoiceTime}}
						 </div>
						 <div class="goods-subtxt"  v-if="tab == 'unHas'">
							 未开票原因：{{item.reason}}
						 </div>
					 </div>
				  </div>
				 <!-- <div class="sale-bottom" v-if="tab == 'has'">
					<span>开票金额：<span style="color:#ff9d02;font-weight: bold">￥{{item.invoiceAmount}}</span></span>
				  </div> -->
				  <div class="sale-btn"  v-if="item.invoiceFiles != ''">
						<u-button text="发票下载" size="small" shape="circle" :custom-style="style2" type="warning" @click="showDown(item)" v-if="tab == 'has'"></u-button>
				  </div>
				</div>
		  </div>
		  
		  <div class="con-list-div" v-else>
				<div class="sale-list-item arrangeGoods-item" v-for="(item,index) in list" :key="index">
				  <div class="sale-top"  style="cursor: pointer">
					<div class="sale-compeny" style="cursor: pointer">{{item.companyName}}</div>
				  </div> 
				  <div class="sale-con" style="cursor: pointer">

					 <div class="goods-middle">
						 <div class="goods-subtxt">纳税人识别号：{{item.licenseCode}}</div>
						 <div class="goods-subtxt">
							 发票类型：{{item.invoiceType == 1 ? '增值税普通发票' : item.invoiceType == 2 ? '增值税专用发票' : '--' }}
						 </div>
					 </div>
				  </div>
				  <div class="sale-btn" style="border-top:0">
						<u-button text="编辑" size="small" shape="circle" :custom-style="style2" type="warning" @click="showSetting(item)"></u-button>
				  </div>
				</div>
		  </div>
		   
		  <div style="padding-bottom:40rpx;" >
			  <u-loadmore :status="status"></u-loadmore>
		  </div>
		  
		  <!--编辑开票信息-->
		  <u-popup :show="show" mode="bottom" :round="10" @close="closeShow">
		   <div class="popupTitle">编辑开票信息</div>
		  	<div class="popup-con" style="height:calc(100vh - 200px);overflow-y: auto;">
		  		<u-form labelPosition="left" :model="form" :rules="rules" ref="form" labelWidth="100" errorType="toast">
		  			<u-form-item required label="发票类型"  borderBottom labelPosition='top'>
						<div style="padding-top:20px" id="invoiceRadio">
							<u-radio-group v-model="form.type">
								<u-radio label="增值税专用发票" :name="2"></u-radio>
								<u-radio label="增值税普通发票" :name="1"></u-radio>
							</u-radio-group>
						</div>	
		  			</u-form-item>
		  			<u-form-item label="发票抬头" borderBottom>
						{{form.title}}
					</u-form-item>
					<u-form-item label="纳税人识别号" borderBottom>
						{{form.taxNumber}}
					</u-form-item>
					<u-form-item label="注册地址" borderBottom>
						<u--input v-model="form.companyAddress" border="none" inputAlign="right" placeholder="请输入"></u--input>
					</u-form-item>
					<u-form-item label="注册电话" borderBottom>
						<u--input v-model="form.telephone" border="none" inputAlign="right" placeholder="请输入"></u--input>
					</u-form-item>
					<u-form-item label="开户银行" borderBottom>
						<u--input v-model="form.bankName" border="none" inputAlign="right" placeholder="请输入"></u--input>
					</u-form-item>
					<u-form-item label="银行帐号" borderBottom>
						<u--input v-model="form.bankAccount" border="none" inputAlign="right" placeholder="请输入"></u--input>
					</u-form-item>
					<u-form-item label="收件人" borderBottom>
						<u--input v-model="form.receivePerson" border="none" inputAlign="right" placeholder="请输入"></u--input>
					</u-form-item>
					<u-form-item label="" borderBottom>
						<uni-data-picker v-slot:default placeholder="请选择所在地区" popup-title="请选择所在地区" :localdata="dataTree"
						  :map="{text:'areaName',value:'areaId'}" @change="onchange" @popupopened="onpopupopened"
						  @popupclosed="onpopupclosed" :clear-icon="false" style="width:100%">
						  <view class="row u-flex" style="width:100%;justify-content: space-between;">
						    <view class="nominal">
						      所在地区
						    </view>
							<div style="display: flex;align-items: center;justify-content: flex-end;">
								<view class="input" style="display: block;">
								  {{areaInfo}}
								</view>
								<u-icon name="arrow-right"></u-icon>
							</div>  
						  </view>
						</uni-data-picker>
					</u-form-item>
					<u-form-item label="详细地址" borderBottom>
						<u--input v-model="form.detailAddress" border="none" inputAlign="right" placeholder="请输入"></u--input>
					</u-form-item>
					<u-form-item label="电话" borderBottom>
						<u--input v-model="form.receiveMobile" border="none" inputAlign="right" placeholder="请输入"></u--input>
					</u-form-item>
					<u-form-item label="上传开票资料" labelPosition='top'>
						<div style="padding-top:10px;" id="invoiceUpdiv">
							<u-upload
							        width="200"
								    height="100"
							        style="width:400rpx;height:200rpx;align-items: center;"
									:fileList="fileList1"
									@afterRead="afterRead"
									@delete="deletePic"
									name="1"
									:maxCount="1"
									:previewFullImage="false"
									imageMode="aspectFit"
								>
								<image :src="form.files" v-if="form.files" mode="aspectFit" style="width: 200px;height: 100px;"></image>
								<div v-else style="border:1px solid #eee;width:400rpx;height:200rpx;margin:0 auto;display: flex;justify-content: center;align-items: center;">
								  <u-icon name="plus" size="30"></u-icon>
								</div>
							</u-upload>
						</div>
					</u-form-item>
		  		</u-form>
		  	</div>
		  	<div class="u-flex popup-bottom">
		  		<u-button text="取消"  shape="circle" @click="closeShow"></u-button>
		  		<u-button text="确认"  shape="circle" type="primary" @click="saveForm" :loading="btnLoading"></u-button>
		  	</div>
		  </u-popup>  
		  
		  <!--发票下载-->
		  <u-popup :show="show2" mode="bottom" :round="10" @close="show2 = false">
		   <div class="popupTitle">发票下载</div>
		  	<div class="popup-con" style="padding-bottom:0" id="inovlceList">
		  		<u-form labelPosition="left" ref="form2" labelWidth="340" errorType="toast">
		  			<u-form-item label="请先选择需要下载发票，暂无发票文件的选项为灰色不可选择" borderBottom labelPosition='top'>
						<div style="padding-top:20px;overflow-y: auto;height:300px">
							<u-radio-group v-model="file" iconPlacement="right" placement="column" :borderBottom="true">
								<u-radio :label="item.invoiceCode" :name="item.file" :disabled="item.file == ''" v-for="item in fileList" :key="item.file" style="padding:8px 0"></u-radio>
							</u-radio-group>
						</div>	
		  			</u-form-item>	
		  		</u-form>
		  	</div>
		  	<div class="u-flex popup-bottom" style="margin-top:0">
		  		<u-button text="取消"  shape="circle" @click="show2 = false"></u-button>
		  		<u-button text="确认"  shape="circle" type="primary" @click="downImg"></u-button>
		  	</div>
		  </u-popup>  
		  
	</view>
</template>

<script>
	const defaultForm={
		     type: 2,
			 title: '',
			 taxNumber: '',
			 bankName: '',
			 bankAccount: '',
			 telephone: '',
			 companyAddress: '',
			 receivePerson: '',
			 province  : '',
			 city : '',
			 area  : '',
			 detailAddress: '',
			 receiveMobile: '',
			 files:''
	    };
	import{imgCheck} from '@/plugins/upload/upload.js'
	import {getInvoiceConfigList,waitInvoiceList,invoiceList,pageSeo,getAreaList,updateInvoiceInfo,getInvoiceConfigDetail} from '@/config/api.js'
	import {setInvoiceDownloadLog} from '@/config/api2.js'
	import {downloadFun} from '@/plugins/utils.js'
	import store from '@/store';
	export default {
	    components:{
	       
	    },
	    data() {
	        return {
				tabs: [
					{key:'has',name:'已开票'},
					{key:'unHas',name:'未开票'},
					],
				status: 'loadmore',
				list: [],
				pageNum: 0,
				pageSize:10,
				count:0,
				orderState:'all',
				current:0,
				style2:{
					width:'160rpx',
					border:'none'
				},
				tab:'has',
		        rules:{
				   type: [{
						required: true,
						message: '请选择发票类型',
						// 可以单个或者同时写两个触发验证方式
						trigger: ['blur', 'change']
					}],
		        				
				},
				form:JSON.parse(JSON.stringify(defaultForm)),
				btnLoading:false,
				show:false,
			    fileList1: [],
				dataTree: [],
				areaInfo:'',
				
				show2:false,
				fileList:[],
				file:null
	        }
	    },
	    async onLoad(e) {
				await this.$onLaunched;
				this.clearData();
				this.getList();
				this.getDataList()
	    },
		async onShow() {
			// #ifdef H5
			pageSeo({pageType: 'indexPage'}).then((res)=>{
				document.title = res.pageTitle;
			})
			// #endif	
		},
		onReachBottom() {
			if(this.list.length >= this.count) {
				this.status = 'nomore';
				return ;
			}
			this.pageNum = ++ this.pageNum;
			if(this.tab != 'set'){
				this.getList()
			}else{
				this.getList2()
			}
			
		},
	    methods: {
			
			toOrder(item){
				uni.navigateTo({
				    url:'/pages/my/orderInfo?orderId='+item.orderId
				})
			},
			showDown(item){
				console.log("item",item)
				this.file = null
				this.fileList = JSON.parse(JSON.stringify(item.invoiceData));
				console.log("this.fileList",this.fileList)
				// this.file = JSON.parse(JSON.stringify(this.fileList[0]['file']))
				this.show2 = true;
			},
			downImg(){
				if(this.file){
					let i = this.fileList.findIndex((el)=>{
					  return el.file == this.file
					})
					setInvoiceDownloadLog({invoiceNo:this.fileList[i]['invoiceCode'],invoiceFile:this.file,deliverId:this.fileList[i]['deliverId']})
					// #ifdef MP
					downloadFun(this.file)	
					// #endif
					// #ifdef H5
					window.open(this.file)
					// #endif
					this.show2 = false
				}else{
					uni.showToast({
						title:'请选择需要下载的发票',
						icon:'none'
					})	
				}
				
				
			},
			onchange(e) {
			  let ids = [];
			  let txts = [];
			  e.detail.value.forEach((item) => {
			    txts.push(item.text)
			    ids.push(item.value)
			  });
			
			  this.form.province = txts[0] ? txts[0] : ''
			  this.form.city = txts[1] ? txts[1] : ''
			  this.form.area = txts[2] ? txts[2] : ''
			  this.areaInfo = txts.join(" ")
			},
			
			getDataList() {
			  getAreaList().then((res) => {
			    this.dataTree = res;
			  })
			},
			
			// 删除图片
			deletePic(event) {
				this.fileList1.splice(0, 1)
				this.form.files = ''
			},
			// 新增图片
			afterRead(event) {
				 if(event.file.size>2*1024*1000){
					uni.showToast({
						title:'图片大小超过2M，请重新选择照片',
						icon:'none'
					})		
					return
				 }
				 uni.showLoading({
					title: '上传中',
				 });
				imgCheck(event.file.url).then((res)=>{
					console.log(res)
					this.fileList1 = [];
					if(res != ''){
						this.fileList1.push({url:res})
					}
					this.form.files = res
					uni.hideLoading()
				}).catch(()=>{
					uni.hideLoading()
				})
			},
			
			showSetting(item){
				this.show = true
				getInvoiceConfigDetail({companyId:item.companyId,invoiceId:item.invoiceId}).then((res)=>{
					this.form = res;
					this.form.companyId = item.companyId;
					this.form.province = res.province
					this.form.city = res.city
					this.form.area = res.area
				    this.areaInfo = res.province+' ' + res.city+' ' + res.area
					this.fileList1 = [];
					if(res.files != ''){
						this.fileList1.push({url:res.files})
					}
					this.form = Object.assign({invoiceId:item.invoiceId}, this.form);
				  })
			},
			
		   saveForm(){
			   this.$refs.form.validate().then(res => {
				   this.btnLoading = true;
				   let  data = JSON.parse(JSON.stringify(this.form));
					 updateInvoiceInfo(data).then(()=>{
						   this.btnLoading = false;
						   this.closeShow();
						   uni.showToast({
							 title: '发票信息编辑成功！',
							 icon: 'none',
							 duration: 2000,
						   });
						   this.getList()
					 }).catch(()=>{
						   this.btnLoading = false;
					 })
			   }).catch(errors => {
				
			   })
		   },
		   
		   closeShow(){
			   this.show = false
		   },
		
			searchList(){
				this.clearData();
				this.getList()
			},
			
			changeTab(tab){
				this.tab = tab.key
				this.clearData()
				this.getList()
				
			},
			
			//清除数据
			clearData(){
					this.pageNum = 1;
					this.list = [];
					this.status = 'loadmore';
					this.count = 0;
			},
			
			getList(){
				let data = {};
				data.pageSize = 10;
				data.pageNum = this.pageNum;
				let fn
				  if(this.tab == 'has'){
					  fn = invoiceList
				  }else if(this.tab == 'unHas'){
					  fn = waitInvoiceList
				  }else if(this.tab == 'set'){
					  fn = getInvoiceConfigList
				  }
				this.status = 'loading';
			    return	fn(data).then((res)=>{
					if(this.tab != 'set'){
					  this.list = this.list.concat(res.list ? res.list : [] );
					  this.count = res.count;
					  if(this.list.length >= this.count) {
					  	this.status = 'nomore';
					  }else{
					  	this.status = 'loadmore';
					  }
					}else{
					  this.list = res;
					  this.status = 'nomore';
					}
					
				}).catch(()=>{
					this.status = 'loadmore';
				})
			},
			
			getList2(){
				let data = {};
				data.pageSize = 10;
				data.pageNum = this.pageNum;
				data.orderState = 'all';
				data.type = 'buyer';
				this.status = 'loading';
			    return	getOrderList(data).then((res)=>{
					this.list = this.list.concat(res.list ? res.list : [] );
					this.count = res.count;
					if(this.list.length >= this.count) {
						this.status = 'nomore';
					}else{
						this.status = 'loadmore';
					}
				}).catch(()=>{
					this.status = 'loadmore';
				})
			},
	    },
	
	}
</script>

<style lang="scss">
@import '@/style/common.scss';
.con-list-div{
    padding:8px 12px;
	.sale-list-item{
		  cursor: pointer;
		  background: #fff;
		  margin-bottom:$marginSpace;
		  border-radius: 8px;
		  font-size:$m-font;
		  line-height: 24px;
		  padding:0 16px;
		  .sale-top{
			  padding-top:5px;
			  line-height:40px;
			  border-bottom:0.8px solid $border-color;
			  @include flexbox(space-between,center);
			  .sale-compeny{
				  @include textoverflow(1);
				  padding-right:16px;
			  }
			  .sale-state{
				  color:$u-primary;
			  }
		  }
		  .sale-con{
			 padding-top:5px; 
			.goods-top{
				@include flexbox(space-between,center);
				.goods-name{
					font-size:$m-font;
					padding-right:20px;
				}
				.goods-price{
					font-size:$m-font;
					font-weight:bold;
					white-space:nowrap;
					.label{
						font-size:10px
					}
				}
			}
			.goods-middle{
				.goods-subtxt{
					font-size:$s-font;
					color:$g-font-color;
				}
			}
		  }
		  .sale-bottom{
			line-height:40px;
			text-align: right;
			color:#888;
		  }
		  .sale-btn{
			padding:10px 0;
			text-align: right;
			border-top:0.8px solid $border-color;
			overflow: hidden;
			@include flexbox(flex-end,center);
		  }

		}
}


.popupTitle{
	font-size:$b-font;
	font-weight: bold;
	text-align: center;
	line-height: 50px;
}
.popup-con{
	padding:0 16px 16px 16px;
}
.popup-con#inovlceList{
	
	.u-radio-label--right{
		padding:8px 0 !important
	}
}
.popup-bottom{
	background: #fff;
	margin-top:10px;
	padding:16px;
}
.popup-bottom-fixed{
	position: fixed;
	width:100%;
	padding:16px;
	box-sizing: border-box;
	bottom:0
}
#invoiceUpdiv .u-upload{
	align-items: center;
}
#invoiceRadio .u-radio{
	margin-right:30px
}
    


</style>

